/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package elaborate.vwbe.impl.scripting;

import elaborate.vwbe.scripting.ScriptEngine;
import elaborate.vwbe.scripting.ScriptEngineContext;
import elaborate.vwbe.scripting.ScriptLanguage;
import elaborate.vwbe.scripting.ScriptingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptException;
import org.w3c.dom.Document;

/**
 *
 * @author lendle
 */
public class DefaultJavaScriptEngine implements ScriptEngine{

    protected javax.script.ScriptEngine _engine;
    protected Document document;
    protected ScriptEngineContext context;
    private List<String> scriptFunctions=new ArrayList<String>();

    /**
     * Get the value of context
     *
     * @return the value of context
     */
    public ScriptEngineContext getContext() {
        return context;
    }

    /**
     * Set the value of context
     *
     * @param context new value of context
     */
    public void setContext(ScriptEngineContext context) {
        this.context = context;
    }


    /**
     * Get the value of document
     *
     * @return the value of document
     */
    public Document getDocument() {
        return document;
    }

    /**
     * Set the value of document
     *
     * @param document new value of document
     */
    public void setDocument(Document document) {
        this.document = document;
    }


    /**
     * Get the value of _engine
     *
     * @return the value of _engine
     */
    public javax.script.ScriptEngine get_engine() {
        return _engine;
    }

    /**
     * Set the value of _engine
     *
     * @param _engine new value of _engine
     */
    public void set_engine(javax.script.ScriptEngine _engine) {
        this._engine = _engine;
    }

    public Object evalScripts(String scripts) throws ScriptingException {
        try {
            if(scripts.trim().startsWith("function")){
                this.scriptFunctions.add(scripts);
            }
            return this._engine.eval(scripts);
        } catch (ScriptException ex) {
            throw new ScriptingException(ex);
        }
    }

    public Object invokeFunction(String functionName, Object... args) throws ScriptingException {
        Invocable invocable=(Invocable) this._engine;
        try {
            return invocable.invokeFunction(functionName, args);
        } catch (Exception ex) {
            throw new ScriptingException(ex);
        }
    }

    public boolean isSupported(ScriptLanguage language) {
        return language.equals(ScriptLanguage.JavaScript);
    }

    public Iterator<String> getDeclaredScriptFunctions() {
        return this.scriptFunctions.iterator();
    }

}
